package com.example.aigc_education.integration.threeparty;
import com.example.aigc_education.integration.impl.ZhipuServiceIntegrationImpl;
import com.example.aigc_education.prompt.ProduceImgPrompts;
import com.example.aigc_education.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
@Slf4j
@Service
public class ZhipuService {
    @Autowired
    private ZhipuServiceIntegrationImpl zhipuServiceIntegration;
    @Autowired
    private AliYunService aliYunService;
    public static MultipartFile convert(String imageUrl) throws IOException {
        URL url = new URL(imageUrl);
        URLConnection connection = url.openConnection();
        String contentType = connection.getContentType();
        InputStream inputStream = connection.getInputStream();

        String fileName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);

        return new MockMultipartFile(fileName, fileName, contentType, inputStream);
    }

    public ResultUtil GenPlanCoverImg(String subject, String title) {
        String prompt = ProduceImgPrompts.generateCoverPrompt(subject, title);
        String url = zhipuServiceIntegration.zhipuGenImg(prompt, "1024x1024");
        MultipartFile multipartFile;
        try {
            multipartFile = convert(url);
        } catch (IOException e) {
            throw new RuntimeException("链接转图片失败");
        }
        return aliYunService.uploadImage(multipartFile);
    }
}
